﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Common
{
    public class MD5Hash
    {
        /// <summary>
        /// 获取字符串MD5编码
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public static string GetstrMD5(string input)
        {
            // Use input string to calculate MD5 hash
            System.Security.Cryptography.MD5 md5 = System.Security.Cryptography.MD5.Create();
            byte[] inputBytes = System.Text.Encoding.Default.GetBytes(input);
            byte[] hashBytes = md5.ComputeHash(inputBytes); 

            // Convert the byte array to hexadecimal string
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < hashBytes.Length; i++)
            {
                sb.Append(hashBytes[i].ToString("X2"));
                // To force the hex string to lower-case letters instead of
                // upper-case, use he following line instead:
                // sb.Append(hashBytes[i].ToString("x2")); 
            }
            return sb.ToString();
        }

        /// 获取文件的MD5码  
        /// </summary>  
        /// <param name="fileName">传入的文件名（含路径及后缀名）</param>  
        /// <returns></returns>  
        public static string GetFileMD5(string fileName)
        {
            StringBuilder sb = new StringBuilder();
            try
            {
                System.IO.FileStream file = new System.IO.FileStream(fileName, System.IO.FileMode.Open);
                System.Security.Cryptography.MD5 md5 = new System.Security.Cryptography.MD5CryptoServiceProvider();
                byte[] retVal = md5.ComputeHash(file);
                file.Close();
                for (int i = 0; i < retVal.Length; i++)
                {
                    sb.Append(retVal[i].ToString("x2"));
                }
                
            }
            catch (Exception ex)
            {
                Common.Log.Error(ex.Message);
            }
            return sb.ToString();
        }
    }
}
